import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_constraintlayout/flutter_constraintlayout.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:wch/model/hospital.dart';
import 'package:wch/native/native.dart';
import 'package:wch/native/net_business.dart';
import 'package:wch/page/home.dart';
import 'package:wch/utils/loading_utils.dart';
import 'package:wch/utils/log_utils.dart';
import 'package:wch/utils/navigator_utils.dart';
import 'package:wch/utils/toast_utils.dart';
import 'package:wch/widget/common_widget.dart';
import 'package:wch/widget/padding_widget.dart';
import 'package:wch/widget/text_widget.dart';

import '../constant/resource_constant.dart';
import '../constant/text_constant.dart';

class SelectHospitalPage extends StatefulWidget {
  SelectHospitalPage({super.key, this.hospital = '', this.hospitalId = '', this.from = 0, required this.hospitalList});
  ///当前医生所属医院
  String hospital;
  String hospitalId;
  int from;
  final List<HospitalData> hospitalList;

  @override
  State<SelectHospitalPage> createState() => _SelectHospitalState();
}

class _SelectHospitalState extends State<SelectHospitalPage> {
  bool isHideListView = false;///是否隐藏医院列表
  double listViewHeight = 40.h * 5;///默认显示5个
  int? selectedIndex;
  String? selectedHospital;
  List<HospitalData> hospitalList = [];

  @override
  void initState() {
    hospitalList = widget.hospitalList;
    selectedHospital = widget.hospital;

    for (int i = 0; i < hospitalList.length; i ++) {
      HospitalData hospitalData = hospitalList[i];
      if (hospitalData.id == widget.hospitalId) {
        selectedIndex = i;
        setState(() {
          selectedHospital = hospitalData.hospitalName;
        });
      }
    }

  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: GestureDetector(
        onTap: (){
          setState(() {
            isHideListView = false;
          });
        },
        child: CommonContainer(
          horPadding: 30,
          child: ConstraintLayout(
            children: [
              BigTitleText(selectHospitalText).applyConstraint(
                top: parent.top.margin(84.h),
                left: parent.left,
              ),
              GestureDetector(
                onTap: (){
                  setState(() {
                    isHideListView = !isHideListView;
                  });
                },
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 10.w),
                  height: 40.h,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(10.h)),
                    border: Border.all(color: themeColor, width: 0.5.h),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      F15TitleText(selectedHospital!, color: F1TextColor),
                      Image.asset(dropDownPng, width: 15, height: 8,),
                    ],
                  ),
                )
              ).applyConstraint(
                  left: parent.left,
                  right: parent.right,
                  top: rId(0).bottom.margin(77.h)
              ),
              Image.asset(hospitalBackgroundPng, width: 100, height: 100,).applyConstraint(
                centerHorizontalTo: parent,
                top: rId(1).bottom.margin(140.h),
                height: 150.h,
                width: 200.w
              ),
              CommonBtn(title: '确定', callback: (){
                if (widget.from == 1) {
                  Loading.getIns().loading(msg: '正在切换医院');
                  String hospitalId = hospitalList[selectedIndex!].id!;
                  NetBusiness().chooseHospital(hospitalId).then((value) {
                    Loading.getIns().hide();
                    if (value) {
                      NavigatorUtil.replace(context, const HomePage());
                      ToastUtils.showToast(msg: '切换医院成功');
                    } else {
                      ToastUtils.showToast(msg: '切换医院失败，请稍后再试');
                    }
                  });
                } else if (selectedHospital == widget.hospital) {
                  NavigatorUtil.pop(context);
                } else {
                  Loading.getIns().loading(msg: '正在切换医院');
                  String hospitalId = hospitalList[selectedIndex!].id!;
                  NetBusiness().chooseHospital(hospitalId).then((value) {
                    Loading.getIns().hide();
                    if (value) {
                      NavigatorUtil.pop(context);
                      ToastUtils.showToast(msg: '切换医院成功');
                    } else {
                      ToastUtils.showToast(msg: '切换医院失败，请稍后再试');
                    }
                  });
                }

              },).applyConstraint(
                left: parent.left,
                right: parent.right,
                top: rId(2).bottom.margin(70.h),
              ),
              Visibility(
                visible: isHideListView,
                maintainInteractivity: false,
                child: Container(
                  height: listViewHeight,
                  width: ScreenUtil().screenWidth-60.w,
                  decoration: BoxDecoration(
                      color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(7.5.h)),
                    boxShadow: const [
                      BoxShadow(
                          color: Colors.black12,
                          offset: Offset(5.0, 5.0), //阴影xy轴偏移量
                          blurRadius: 15.0, //阴影模糊程度
                          spreadRadius: 1.0 //阴影扩散程度
                      )
                    ]
                  ),
                  child: SingleChildScrollView(
                    child: Column(
                      children: _getHospitalList(),
                    ),
                  )
                ),
              ).applyConstraint(
                  top: rId(1).bottom.margin(5.h),
                  left: parent.left,
                  right: parent.right,
                  height: listViewHeight
              ),
            ]
          ),
        ),
      ),
    );
  }

  List<Widget> _getHospitalList() {
    if (hospitalList!.isEmpty){
      return [];
    }

    List<Widget> list = [];
    for(int i = 0; i < hospitalList.length; i ++) {
      list.add(_getHospitalItem(i, selectedIndex == i));
    }

    return list;
  }

  Widget _getHospitalItem(int index, bool isSelected) {
    return GestureDetector(
      onTap: (){
        setState(() {
          selectedHospital = hospitalList[index].hospitalName!;
          isHideListView = false;
          selectedIndex = index;
        });
      },
      child: Container(
        alignment: Alignment.centerLeft,
        height: 40.h,
        width: ScreenUtil().screenWidth-60.w,
        padding: EdgeInsets.symmetric(horizontal: 20.w),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(7.5.h)),
          color: isSelected ? Color(0xFFF3F6FF) : Colors.white
        ),
        child: F14TitleText(
          hospitalList[index].hospitalName!,
          color: F1TextColor,
        ),
      ),
    );
  }
}
